package com.njupt.StackAndQueue;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/16 21:04
 * @Description: 150 逆波兰表达式求值
 * @Version: 1.0
 */


public class EvalRPN {

    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new LinkedList<Integer>();

        for (int i = 0; i < tokens.length; i++) {
            if(!IsOpter(tokens[i])){
                stack.push(Integer.valueOf(tokens[i]));
            }else {
                int rightNum = stack.pop();
                int leftNum = stack.pop();
                if(tokens[i].equals("+")){
                    stack.push(leftNum + rightNum);
                } else if (tokens[i].equals("-")) {
                    stack.push(leftNum - rightNum);
                }else if (tokens[i].equals("*")) {
                    stack.push(leftNum * rightNum);
                }else  {
                    stack.push(leftNum / rightNum);
                }
            }
        }


        return stack.pop();
    }

    private boolean IsOpter(String token) {
        if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        String[] tokens = {"2","1","+","3","*"};
        EvalRPN test = new EvalRPN();
        System.out.println(test.evalRPN(tokens));
    }
}
